package com.xbai.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xbai.common.utils.R;
import com.xbai.common.utils.ResponseUtil;
import com.xbai.security.entity.SecurityUser;
import com.xbai.security.entity.User;
import com.xbai.security.security.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author xbai
 * @Date 2021/4/26
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    private RedisTemplate redisTemplate;

    private TokenManager tokenManager;

    public TokenLoginFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate, TokenManager tokenManager) {
        this.authenticationManager = authenticationManager;
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login", "POST"));
    }

    /**
     * 获取表单提交的用户名和密码
     * @param request {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @return {@link Authentication}
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //获取表单提交数据
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                    new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 认证成功调用的方法
     * @param request {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @param chain {@link FilterChain}
     * @param authResult {@link Authentication}
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) {
        // 认证成功，得到认证成功的用户信息
        SecurityUser user = (SecurityUser) authResult.getPrincipal();
        // 根据用户名生成 token
        String username = user.getCurrentUserInfo().getUsername();
        String token = tokenManager.createToken(username);
        // 把用户名称和用户权限列表放到 redis
        redisTemplate.opsForValue().set(username, user.getPermissionValueList());
        // 返回 token
        ResponseUtil.out(response, R.ok().data("token", token));
    }

    /**
     * 认证失败调用的方法
     * @param request {@link HttpServletRequest}
     * @param response {@link HttpServletResponse}
     * @param failed {@link AuthenticationException}
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
        ResponseUtil.out(response, R.error().message(failed.getMessage()));
    }
}
